package com.aaa.inside.controller;


import com.aaa.entity.base.Locator;
import com.aaa.entity.inside.Move;
import com.aaa.entity.inside.Puton;
import com.aaa.entity.stock.Stock;
import com.aaa.entity.system.User;
import com.aaa.inside.feign.BaseFeign;
import com.aaa.inside.feign.StockFeign;
import com.aaa.inside.feign.SystemFeign;
import com.aaa.inside.service.MoveService;
import com.aaa.inside.service.PutonService;
import com.aaa.inside.util.JwtUtils;
import com.aaa.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author aaa
 * @since 2020-11-27
 */
@RestController
@RequestMapping("/inside/move")
public class MoveController {
    @Autowired
    private MoveService moveService;
    @Autowired
    private StockFeign stockFeign;
    @Autowired
    private PutonService putonService;
    @Autowired
    private BaseFeign baseFeign;
    @Autowired
    private SystemFeign systemFeign;
    /*通过仓库id查询所有库存中所有商品名称和编码*/
    @PostMapping("selectComByWareId")
    @ApiOperation("通过仓库id查询所有库存中的所有商品名称和编码")
    public List<Map> selectComByWareId(){
        Long warehouseid=41L;
        return moveService.selectComByWareId(warehouseid);
    }
    /*通过商品编号和仓库id查询该商品在该仓库的所有源货位*/
    @PostMapping("selectOriLocByCombar/{commoditybar}")
    @ApiOperation("通过商品编号和仓库id查询该仓库的源货位")
    public List<Map> selectOriLocByCombar(@PathVariable String commoditybar){
        Long warehouseid=41L;
        return moveService.selectOriLocByCombar(commoditybar,warehouseid);
    }
    /*通过源货位编码查出同类型的所有可移库的目标货位*/
    @ApiOperation("通过源货位编码查出同类型的所有可移库的目标货位")
    @PostMapping("selectTarLocByOrLoc/{oldlocatorcode}")
    public List<Map> selectTarLocByOrLoc(@PathVariable String oldlocatorcode){
        Long warehouseid=41L;
        return moveService.selectTarLocByOrLoc(oldlocatorcode,warehouseid);
    }

    @ApiOperation("移库操作")
    @PostMapping("addMove")
    public R move(@RequestBody Move move, HttpServletRequest request){
        if (move.getQty()==0){
            return R.error().message("数量不能为0");
        }
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);

        /*查出库存中待移库的一个商品*/
        Long warehouseid=41L;
        Stock stock=stockFeign.selectStockByComBarOriLo(move.getCommoditybar(),move.getOldlocatorcode(),warehouseid);
        /*通过商品编码查出商品名称和id*/
        Map comList=putonService.selectCommoditynameByBar(move.getCommoditybar());
        Long commodityid= (Long) comList.get("id");
        String commodityname= (String) comList.get("name");
        /*通过源货位编码查出源货位id和名称*/
        Map OldLoIdName=putonService.selectOriLoIdNameByOldLoCode(move.getOldlocatorcode());
        Long oldlocatorid= (Long) OldLoIdName.get("id");
        String oldlocatorname= (String) OldLoIdName.get("name");
        /*通过目标货位编码查出目标货位id和名称状态和类型整个实体*/
        Locator locator= baseFeign.selectTarLocByLoCode(move.getLocatorcode(),warehouseid);
        if(move.getQty()<=stock.getUqty()){
            QueryWrapper<Move> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("commoditybar",move.getCommoditybar());
            queryWrapper.eq("oldlocatorcode",move.getOldlocatorcode());
            queryWrapper.eq("locatorcode",move.getLocatorcode());
            queryWrapper.eq("state","1");
            Move move2 = moveService.getOne(queryWrapper);
            if (move2!=null){
                move2.setQty(move2.getQty()+move.getQty());
                moveService.updateById(move2);
                stock.setUqty(stock.getUqty()-move.getQty());
                stock.setLqty(stock.getLqty()+move.getQty());
                stockFeign.updateById(stock);
                return R.ok().message("移库成功");
            }



            Move move1=new Move();
            move1.setCommoditybar(move.getCommoditybar());
            move1.setCommodityname(commodityname);
            move1.setCommodityid(commodityid);
            move1.setLocatorid(locator.getId());
            move1.setLocatorcode(locator.getCode());
            move1.setLocatorname(locator.getName());
            move1.setOldlocatorid(oldlocatorid);
            move1.setOldlocatorcode(move.getOldlocatorcode());
            move1.setOldlocatorname(oldlocatorname);
            move1.setQty(move.getQty());
            move1.setWarehouseid(warehouseid);
            move1.setCreateid(user.getUserId());
            move1.setCreator(user.getName());
            Date now=new Date();
            move1.setCreatetime(now);
            moveService.save(move1);

            stock.setUqty(stock.getUqty()-move.getQty());
            stock.setLqty(stock.getLqty()+move.getQty());
            stockFeign.updateById(stock);
            return R.ok().message("移库成功");
        }else {
            return R.error().message("源库位商品数量不足，请核实！");
        }
    }
    /*移库管理审核操作*/
    @PostMapping("moveCheck")
    @ApiOperation("移库管理审核操作")
    public R moveCheck(@RequestBody Move move,HttpServletRequest request) {
        String token = request.getHeader("token");
        Long userid = JwtUtils.getMemberIdByJwtToken(token);
        User user = systemFeign.selectUserById(userid);
        Long warehouseid = 41L;
        if (move.getState().equals("1")) {
            /*库存中对应的源库位商品数量更新*/
            Stock stock = stockFeign.selectStockByComBarOriLo(move.getCommoditybar(), move.getOldlocatorcode(), warehouseid);

            if (stock.getUqty() == 0) {
                stockFeign.removeById(stock.getId());
            }

            stock.setCqty(stock.getUqty());
            stock.setLqty(stock.getLqty() - move.getQty());
            stockFeign.updateById(stock);


            Stock stock1 = new Stock();
            stock1.setLocatorid(move.getLocatorid());
            stock1.setLocatorcode(move.getLocatorcode());
            stock1.setLocatorname(move.getLocatorname());
            stock1.setCommodityid(move.getCommodityid());
            stock1.setCommoditybar(move.getCommoditybar());
            stock1.setCommodityname(move.getCommodityname());
            stock1.setWarehouseid(warehouseid);

            /*判断库存有没有目标同货位同商品的数据有更新没有插入*/
            Stock stock2 = stockFeign.selectStockByComBarOriLo(move.getCommoditybar(), move.getLocatorcode(), warehouseid);
            if (stock2 == null) {
                stock1.setLqty(0);
                stock1.setCqty(move.getQty());
                stock1.setUqty(move.getQty());
                stockFeign.save(stock1);
            } else {
                stock2.setCqty(stock2.getCqty() + move.getQty());
                stock2.setUqty(stock2.getUqty() + move.getQty());
                QueryWrapper<Stock> queryWrapper = new QueryWrapper<>();
                Map map=new HashMap();
                map.put("locatorcode", move.getLocatorcode());
                map.put("commoditybar", move.getCommoditybar());
                map.put("warehouseid",warehouseid);
                stockFeign.update(stock2, map);
            }
            move.setState("2");
            move.setAuditor(user.getName());
            Date now=new Date();
            move.setAudittime(now);
            moveService.updateById(move);
            return R.ok().message("审核成功");
        }else {
            return R.error().message("已审核请勿重复操作");
        }
    }
    /*移库撤销审核操作*/
    @PostMapping("moveCancelCheck")
    @ApiOperation("移库撤销审核操作")
    public R moveCancelCheck(@RequestBody Move move){
        Long warehouseid=41L;
        if (move.getState().equals("1")){
            return  R.error().message("此订单尚未审核，请先审核！");
        }
        Stock stock = stockFeign.selectStockByComBarOriLo(move.getCommoditybar(), move.getOldlocatorcode(),warehouseid);
        if (stock==null){
            Stock stock1=new Stock();
            stock1.setCqty(move.getQty());
            stock1.setUqty(0);
            stock1.setLqty(move.getQty());
            stock1.setLocatorid(move.getOldlocatorid());
            stock1.setLocatorcode(move.getOldlocatorcode());
            stock1.setLocatorname(move.getOldlocatorname());
            stock1.setCommodityid(move.getCommodityid());
            stock1.setCommoditybar(move.getCommoditybar());
            stock1.setCommodityname(move.getCommodityname());
            stockFeign.save(stock1);
        }else {
            stock.setCqty(stock.getUqty() + move.getQty());
            stock.setLqty(move.getQty());
            stockFeign.updateById(stock);
        }

        Stock stock2 = stockFeign.selectStockByComBarOriLo(move.getCommoditybar(), move.getLocatorcode(),warehouseid);
        if(stock2.getCqty()==move.getQty()){
            stockFeign.removeById(stock2.getId());
        }else {
            stock2.setUqty(stock2.getUqty()-move.getQty());
            stock2.setCqty(stock2.getCqty()-move.getQty());
            stockFeign.updateById(stock2);
        }
        /*审核状态变成未审核*/
        move.setState("1");
        moveService.updateById(move);
        return R.ok().message("撤销审核成功");
    }

    /*分页按条件查询所有移库管理*/
    @PostMapping("searchMove/{page}/{limit}")
    @ApiOperation("分页按条件查询所有移库管理")
    public R searchMove(@PathVariable Integer page, @PathVariable Integer limit, @RequestBody Move move){
        return moveService.searchMove(page,limit,move);
    }

    /*删除上架管理*/
    @PostMapping("deleteMove")
    public R deletePuton(@RequestBody Move move){
        boolean b = moveService.removeById(move.getId());
        if(b){
            Stock stock=stockFeign.selectStockByComBarOriLo(move.getCommoditybar(),move.getOldlocatorcode(),41L);
            stock.setLqty(stock.getLqty()-move.getQty());
            stock.setUqty(stock.getUqty()+move.getQty());
            Boolean a = stockFeign.updateById(stock);
            if (a){
                return R.ok().message("删除成功");
            }else {
                return R.error().message("删除失败");
            }
        }else {
            return R.error().message("删除失败");
        }

    }
}

